<?php

namespace catchAdmin\apidoctor\controller;

use app\common\model\PatientInfo as PatientModel;
use catchAdmin\archives\service\CollectService;
use catcher\base\CatchRequest;
use catcher\CatchResponse;
use catcher\base\CatchController;
use catcher\exceptions\FailedException;
use catchAdmin\registration\service\TaskService;
use app\common\model\CollectCase as CollectCaseModel;
use app\common\model\CollectClass as CollectClassModel;
use app\common\model\PropagandaEducation as PropagandaEducationModel;
use think\exception\ValidateException;
use catchAdmin\apidoctor\validate\RcValidate;
use catchAdmin\permissions\model\Department as DepartmentModel;
use catchAdmin\propaganda\service\EdCenterService;


class Rc extends CatchController
{
    protected $domain = null;

    public function __construct()
    {
        $this->domain = new \app\common\business\Contract();
    }

    /**
     * 获取收案分类
     * @param CatchRequest $request
     * @return \think\response\Json
     */
    public function get_rc_class(CatchRequest $request): \think\response\Json
    {
        $list = (new CollectClassModel())->getLists(1, request()->userInfo['id']);
        array_unshift($list, ["className"=>"未分组","parent_id"=>"0","id"=>"-2","count"=>0]);
        return CatchResponse::success($list);
    }

    /**
     * 新增收案分类
     * @param CatchRequest $request
     * @return \think\response\Json
     */
    public function create_doctor_case_class(CatchRequest $request): \think\response\Json
    {
        $req = $request->param();
        $req['deleted_at'] = 0;
        $req['creator_id'] = request()->userInfo['id'];

        if (empty($req['className'])) {
            throw new FailedException("分类名称不能为空");
        }
        if (!empty($req['is_share']) == 1 && empty($req['manageList'])) {
            throw new FailedException("管理人员不能为空");
        }
        return CatchResponse::success((new CollectService())->addCollectClass($req));
    }

    /**
     * 获取收案患者
     * @param CatchRequest $request
     * @return \think\response\Json
     */
    public function get_rc_case_list(CatchRequest $request): \think\response\Json
    {
        $req = $request->param();

        #验证参数
        try {
            validate(RcValidate::class)
                ->scene('get_rc_case_list')
                ->check($req);
        } catch (ValidateException $e) {
            return CatchResponse::fail($e->getError());
        }

        return CatchResponse::success((new CollectCaseModel())->getYsdCase($req['class_id']));
    }

    /**
     * 批量分组
     * @param CatchRequest $request
     * @return \think\response\Json
     */
    public function batch_rc_grouping(CatchRequest $request): \think\response\Json
    {
        $creator_id = request()->userInfo['id'];

        $groupId = $request->param("class_id", 0, 'string');

        $type = $request->param("type", 1, "int");

        $patientList = $request->param("patient_list", []);
        if (empty($patientList)) {
            throw new FailedException("患者列表不存在");
        }
        $patients = (new PatientModel())->whereIn('id', $patientList)->field('id,patientId,sex,name')->select()->toArray();
        $patientLists = [];
        foreach ($patients as $key => $val)
        {
            $data['patient_uuid'] = $val['id'];
            $data['patient_id']   = $val['patientId'];
            $data['sex']          = $val['sex'];
            $data['name']         = $val['name'];
            $patientLists[] = $data;
        }

        $result = $this->domain->grouping($patientLists, $groupId, $creator_id, $type);
        if ($result) {
            return CatchResponse::success("分组成功");
        }
        return CatchResponse::fail("分组失败");
    }

    /**
     * 获取宣教类别树型
     *
     * @param CatchRequest $request
     * @return \think\response\Json
     */
    public function get_ysd_education_tree()
    {
        return CatchResponse::success((new PropagandaEducationModel)->getDatas());
    }

    /**
     * 发送宣教
     *
     * @param CatchRequest $request
     * @return \think\response\Json
     */
    public function push_ysd_education(CatchRequest $request): \think\response\Json
    {
        $req = $request->param();
        if (!isset($req['batch_name']) || empty($req['batch_name'])) {
            throw new FailedException('宣教计划名称不能为空');
        }
        $req['doctor_code'] = request()->userInfo['doctor_code'];
        $req['pushtime'] = date("Y-m-d H:i", strtotime($req['pushtime']));
        return CatchResponse::success((new EdCenterService())->pushData($req));
    }

    /**
     * 创建随访计划
     * @param CatchRequest $request
     * @return \think\response\Json
     */
    public function create_ysd_follow(CatchRequest $request): \think\response\Json
    {
        $req = $request->param();
        $userInfo = request()->userInfo;

        $req['creator_id'] = $userInfo['id'];
        $req['deleted_at'] = 0;
        $req['follow_staff'][] = [
            'user_id' => $userInfo['id'],
            'username' => $userInfo['username'],
            'doctor_code' => $userInfo['doctor_code'],
            'department_id' => $userInfo['department_id'],
            'department_name' => (new DepartmentModel())->where('id',$userInfo['department_id'])->value('department_name')
        ];
        if (!empty($req['pushtime'])) {
            $req['pushtime'] = date('Y-m-d H:i', strtotime($req['pushtime']));
        }
        return CatchResponse::success((new TaskService)->saveTask($req));
    }

    /**
     * 模糊搜索收案患者
     * @param CatchRequest $request
     * @return \think\response\Json
     */
    public function like_case_patient(CatchRequest $request): \think\response\Json
    {
        $name = $request->param('name');
        return CatchResponse::success((new CollectCaseModel)->searchCasePatient(request()->userInfo['id'], $name));
    }
}